<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { onMounted, ref, computed } from 'vue';
import { 
  getArticleDetail, 
  likeArticle, 
  cancelLikeArticle, 
  deleteArticle,
  publishComment,
  deleteComment,
  publishSecondComment,
  deleteSecondComment,
  likeComment,
  cancelLikeComment
} from '@/api/community';
import { getUserInfoById } from '@/api/user';
import { ArticleDetail, Comment, SecondComment } from '@/api/community/type';
import { User } from '@/api/user/type';
import { showSuccessToast, showFailToast, showConfirmDialog } from 'vant';
import { useUserStore } from '@/store/user';

interface CommentWithUser extends Comment {
  user?: User;
}

interface SecondCommentWithUser extends SecondComment {
  user?: User;
}

interface ArticleDetailWithUsers extends ArticleDetail {
  author?: User;
  commentsWithUsers: CommentWithUser[];
  secondCommentsWithUsers: SecondCommentWithUser[];
}

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const articleId = route.params.id as string;

const article = ref<ArticleDetailWithUsers | null>(null);
const loading = ref(true);
const commentContent = ref('');
const replyTo = ref<{ commentId: string; username: string; content: string } | null>(null);
const likeDebounce = ref<{[key: string]: {timestamp: number, processing: boolean}}>({});

const currentUserId = computed(() => userStore.getId || '');

const isArticleAuthor = computed(() => 
  currentUserId.value && article.value?.authorId === currentUserId.value
);

const fetchArticleDetail = async () => {
  try {
    loading.value = true;
    const response = await getArticleDetail(articleId);
    if (response.data) {
      const articleData = response.data as ArticleDetail;
      
      let author: User | undefined;
      try {
        const authorResponse = await getUserInfoById(articleData.authorId);
        author = authorResponse.data;
      } catch (error) {
        console.error('获取文章作者信息失败:', error);
      }

      const commentsWithUsers = await Promise.all(articleData.comments.map(async (comment) => {
        let user: User | undefined;
        try {
          const userResponse = await getUserInfoById(comment.userId);
          user = userResponse.data;
        } catch (error) {
          console.error('获取评论用户信息失败:', error);
        }
        return { ...comment, user } as CommentWithUser;
      }));

      const secondCommentsWithUsers = await Promise.all(articleData.secondComments.map(async (comment) => {
        let user: User | undefined;
        try {
          const userResponse = await getUserInfoById(comment.userId);
          user = userResponse.data;
        } catch (error) {
          console.error('获取二级评论用户信息失败:', error);
        }
        return { ...comment, user } as SecondCommentWithUser;
      }));

      article.value = {
        ...articleData,
        author,
        commentsWithUsers,
        secondCommentsWithUsers
      };
      
      console.log('文章详情(处理后):', article.value);
    }
  } catch (error) {
    console.error('获取文章详情失败:', error);
    showFailToast('获取文章详情失败');
  } finally {
    loading.value = false;
  }
};

const handleLikeArticle = async () => {
  if (!article.value) return;
  
  const now = Date.now();
  const key = `article_${articleId}`;
  
  if (likeDebounce.value[key]) {
    if (likeDebounce.value[key].processing) return;
    if (now - likeDebounce.value[key].timestamp < 1000) {
      showFailToast('操作太频繁，请稍后再试');
      return;
    }
  }
  
  likeDebounce.value[key] = { timestamp: now, processing: true };
  
  const isLiked = article.value.isLike;
  const originalLikeCount = article.value.likeCount || '0';
  
  article.value.isLike = !isLiked;
  
  article.value.likeCount = String(
    isLiked 
      ? Math.max(0, parseInt(originalLikeCount) - 1) 
      : parseInt(originalLikeCount) + 1
  );
  
  try {
    if (isLiked) {
      await cancelLikeArticle(articleId);
    //   showSuccessToast('已取消点赞');
    } else {
      await likeArticle(articleId);
    //   showSuccessToast('点赞成功');
    }
  } catch (error: any) {
    article.value.isLike = isLiked;
    article.value.likeCount = originalLikeCount;
    
    // if (error.response?.data?.code === 4010) {
    //   showFailToast('你已经点赞该文章');
    // } else if (error.response?.data?.code === 4011) {
    //   showFailToast('你已经取消点赞该文章');
    // } else {
    //   showFailToast('操作失败，请稍后重试');
    // }
  } finally {
    if (likeDebounce.value[key]) {
      likeDebounce.value[key].processing = false;
    }
  }
};

const handleLikeComment = async (comment: CommentWithUser | SecondCommentWithUser, isSecondComment = false) => {
  const now = Date.now();
  const key = `comment_${comment.id}`;
  
  if (likeDebounce.value[key]) {
    if (likeDebounce.value[key].processing) return;
    if (now - likeDebounce.value[key].timestamp < 1000) {
      showFailToast('操作太频繁，请稍后再试');
      return;
    }
  }
  
  likeDebounce.value[key] = { timestamp: now, processing: true };
  
  const originalIsLike = comment.isLike;
  const originalLikeCount = comment.likeCount || '0';
  
  comment.isLike = !originalIsLike;
  comment.likeCount = String(
    originalIsLike 
      ? Math.max(0, parseInt(originalLikeCount) - 1) 
      : parseInt(originalLikeCount) + 1
  );
  
  try {
    if (originalIsLike) {
      await cancelLikeComment(comment.id);
    //   showSuccessToast('已取消点赞');
    } else {
      await likeComment(comment.id);
    //   showSuccessToast('点赞成功');
    }
  } catch (error: any) {
    comment.isLike = originalIsLike;
    comment.likeCount = originalLikeCount;
    
    // if (error.response?.data?.code === 4010) {
    //   showFailToast('你已经点赞该评论');
    // } else if (error.response?.data?.code === 4011) {
    //   showFailToast('你已经取消点赞该评论');
    // } else {
    //   showFailToast('操作失败，请稍后重试');
    // }
  } finally {
    if (likeDebounce.value[key]) {
      likeDebounce.value[key].processing = false;
    }
  }
};

const handleDeleteArticle = async () => {
  try {
    await showConfirmDialog({
      title: '删除文章',
      message: '确定要删除这篇文章吗？'
    });
    
    const response = await deleteArticle(articleId);
    if (response) {
      showSuccessToast('删除成功');
      router.back();
    }
  } catch (error) {
    console.error('删除文章失败:', error);
  }
};

const handleDeleteComment = async (commentId: string, isSecondComment = false) => {
  try {
    await showConfirmDialog({
      title: '删除评论',
      message: '确定要删除这条评论吗？'
    });
    
    if (isSecondComment) {
      await deleteSecondComment(commentId);
    } else {
      await deleteComment(commentId);
    }
    
    showSuccessToast('删除成功');
    await fetchArticleDetail();
  } catch (error) {
    console.error('删除评论失败:', error);
    showFailToast('删除评论失败');
  }
};

const handlePublishComment = async () => {
  if (!commentContent.value.trim()) {
    showFailToast('评论内容不能为空');
    return;
  }
  
  try {
    if (replyTo.value) {
      await publishSecondComment({
        parentCommentId: replyTo.value.commentId,
        articleId: articleId,
        content: commentContent.value.trim()
      });
      replyTo.value = null;
    } else {
      await publishComment({
        articleId: articleId,
        content: commentContent.value.trim()
      });
    }
    
    commentContent.value = '';
    showSuccessToast('评论成功');
    await fetchArticleDetail();
  } catch (error) {
    console.error('发表评论失败:', error);
    showFailToast('发表评论失败');
  }
};

const setReplyTo = (commentId: string, username: string, content: string = '') => {
  replyTo.value = { 
    commentId, 
    username,
    content: content.length > 30 ? content.substring(0, 30) + '...' : content 
  };
  focusCommentInput();
};

const focusCommentInput = () => {
  document.getElementById('commentInput')?.focus();
};

const cancelReply = () => {
  replyTo.value = null;
};

const goBack = () => {
  router.back();
};

const getCommentReplies = (commentId: string) => {
  if (!article.value) return [];
  return article.value.secondCommentsWithUsers.filter(
    comment => comment.parentCommentId === commentId
  );
};

onMounted(fetchArticleDetail);
</script>

<template>
  <div class="article-detail">
    <!-- 自定义顶栏替换 vant 组件 -->
    <div class="custom-header">
      <div class="back-button" @click="goBack">
        <i class="icon-back"></i>
      </div>
      <div class="header-title">文章详情</div>
      <div class="placeholder"></div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px">加载中...</van-loading>
    </div>
    
    <template v-else-if="article">
      <div class="article-content">
        <!-- 文章头部 -->
        <div class="article-header">
          <van-image 
            round 
            width="40" 
            height="40" 
            :src="article.author?.avatar"
          />
          <div class="author-info">
            <div class="author-name">{{ article.author?.nickname }}</div>
            <div class="publish-time">{{ new Date(article.comments[0]?.created || '').toLocaleDateString() }}</div>
          </div>
          
          <van-button 
            v-if="isArticleAuthor" 
            size="small" 
            type="danger" 
            class="delete-btn"
            @click="handleDeleteArticle"
          >
            删除
          </van-button>
        </div>
        
        <!-- 文章内容 -->
        <div class="article-body">
          <p>{{ article.content }}</p>
        </div>
        
        <!-- 文章操作栏 -->
        <div class="article-actions">
          <van-button
            class="action-btn"
            :class="{ 'active': article.isLike }"
            :icon="article.isLike ? 'like' : 'like-o'"
            :type="article.isLike ? 'danger' : 'default'"
            block
            size="small"
            plain
            @click="handleLikeArticle"
          >
            {{ article.likeCount || '0' }}
          </van-button>
          
          <van-button
            class="action-btn"
            icon="comment-o"
            size="small"
            block
            plain
            @click="focusCommentInput"
          >
            {{ article.commentCount || '0' }}
          </van-button>
          
          <van-button
            class="action-btn"
            icon="share-o"
            size="small"
            block
            plain
          >
            分享
          </van-button>
        </div>
      </div>
      
      <!-- 评论列表 -->
      <div class="comment-section">
        <div class="comment-header">
          <h3>全部评论 ({{ article.commentCount || '0' }})</h3>
        </div>
        
        <div v-if="article.commentsWithUsers && article.commentsWithUsers.length > 0">
          <div v-for="comment in article.commentsWithUsers" :key="comment.id" class="comment-item">
            <div class="comment-container">
              <van-image
                round
                width="36"
                height="36"
                :src="comment.user?.avatar"
                class="comment-avatar"
              />
              
              <div class="comment-content">
                <div class="comment-user">{{ comment.user?.nickname }}</div>
                <div class="comment-text">{{ comment.content }}</div>
                
                <div class="comment-actions">
                  <span class="comment-time">{{ new Date(comment.created).toLocaleString() }}</span>
                  
                  <div class="comment-btns">
                    <van-button
                      class="comment-btn"
                      :class="{ 'active': comment.isLike }"
                      :icon="comment.isLike ? 'like' : 'like-o'"
                      size="mini"
                      plain
                      @click="handleLikeComment(comment)"
                    >
                      {{ comment.likeCount || '0' }}
                    </van-button>
                    
                    <van-button
                      class="comment-btn"
                      icon="comment-o"
                      size="mini"
                      plain
                      @click="setReplyTo(comment.id, comment.user?.nickname || '', comment.content)"
                    >
                      回复
                    </van-button>
                    
                    <van-button
                      v-if="currentUserId === comment.userId"
                      class="comment-btn delete-btn"
                      icon="delete-o"
                      size="mini"
                      plain
                      @click="handleDeleteComment(comment.id)"
                    />
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 二级评论 -->
            <div class="replies-container">
              <div 
                v-for="reply in getCommentReplies(comment.id)" 
                :key="reply.id"
                class="reply-item"
              >
                <van-image
                  round
                  width="28"
                  height="28"
                  :src="reply.user?.avatar"
                  class="comment-avatar"
                />
                
                <div class="comment-content">
                  <div class="comment-user">{{ reply.user?.nickname }}</div>
                  <div class="comment-text">{{ reply.content }}</div>
                  
                  <div class="comment-actions">
                    <span class="comment-time">
                      {{ reply.created ? new Date(reply.created).toLocaleString() : '刚刚' }}
                    </span>
                    
                    <div class="comment-btns">
                      <van-button
                        class="comment-btn"
                        :class="{ 'active': reply.isLike }"
                        :icon="reply.isLike ? 'like' : 'like-o'"
                        size="mini"
                        plain
                        @click="handleLikeComment(reply, true)"
                      >
                        {{ reply.likeCount || '0' }}
                      </van-button>
                      
                      <van-button
                        class="comment-btn"
                        icon="comment-o"
                        size="mini"
                        plain
                        @click="setReplyTo(comment.id, reply.user?.nickname || '', reply.content)"
                      >
                        回复
                      </van-button>
                      
                      <van-button
                        v-if="currentUserId === reply.userId"
                        class="comment-btn delete-btn"
                        icon="delete-o"
                        size="mini"
                        plain
                        @click="handleDeleteComment(reply.id, true)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-comments">
          <p>暂无评论，快来抢沙发吧！</p>
        </div>
      </div>
    </template>
    
    <div v-else class="error-container">
      <p>文章不存在或已被删除</p>
      <van-button type="primary" @click="goBack">返回</van-button>
    </div>
    
    <!-- 评论输入框 -->
    <div class="comment-input-container">
      <div v-if="replyTo" class="reply-info">
        <div class="reply-text">
          <span class="reply-username">回复 {{ replyTo.username }}:</span>
          <span class="reply-content">{{ replyTo.content }}</span>
        </div>
        <van-icon name="cross" @click="cancelReply" class="reply-close" />
      </div>
      
      <van-field
        id="commentInput"
        v-model="commentContent"
        rows="1"
        autosize
        type="textarea"
        placeholder="发表你的评论..."
        class="comment-input"
      >
        <template #button>
          <van-button 
            size="small" 
            type="primary" 
            :disabled="!commentContent.trim()"
            @click="handlePublishComment"
          >
            发送
          </van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<style scoped>
.article-detail {
  display: flex;
  flex-direction: column;
  background-color: #f7f8fa;
  padding-top: 46px;
  position: relative;
  height: 100%;
}

.custom-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 46px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.back-button {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.icon-back {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-top: 2px solid #333;
  border-left: 2px solid #333;
  transform: rotate(-45deg);
}

.header-title {
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  flex: 1;
}

.placeholder {
  width: 30px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  height: 300px;
}

.article-content {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 8px;
}

.article-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.author-info {
  margin-left: 12px;
  flex: 1;
}

.author-name {
  font-weight: bold;
  font-size: 14px;
}

.publish-time {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.delete-btn {
  margin-left: auto;
}

.article-body {
  font-size: 16px;
  line-height: 1.6;
  margin: 12px 0;
  word-break: break-word;
}

.article-actions {
  display: flex;
  justify-content: space-around;
  border-top: 1px solid #eee;
  padding-top: 12px;
  margin-top: 12px;
}

.action-btn {
  flex: 1;
  margin: 0 8px;
  height: 36px;
}

.action-btn.active {
  color: #ee0a24;
}

.comment-section {
  flex: 1;
  background-color: #fff;
  padding: 0 16px;
  padding-bottom: 60px;
}

.comment-header {
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.comment-item {
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.comment-container {
  display: flex;
}

.comment-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 4px;
}

.comment-text {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 8px;
  word-break: break-word;
}

.comment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.comment-time {
  color: #999;
}

.comment-btns {
  display: flex;
  align-items: center;
}

.comment-btn {
  margin-left: 8px;
}

.comment-btn.active {
  color: #ee0a24;
}

.replies-container {
  margin-left: 48px;
  margin-top: 8px;
}

.reply-item {
  display: flex;
  padding: 8px 0;
  border-top: 1px solid #f5f5f5;
}

.empty-comments {
  padding: 24px 0;
  text-align: center;
  color: #999;
}

.comment-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 8px;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
}

.reply-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  margin-bottom: 8px;
}

.reply-text {
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 12px;
  margin-right: 8px;
}

.reply-username {
  color: #666;
  margin-right: 4px;
  font-weight: bold;
}

.reply-content {
  color: #999;
}

.reply-close {
  flex-shrink: 0;
  padding: 4px;
}

.comment-input {
  width: 100%;
}
</style>
